﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using TransFormer.Model;
using TransFormer.Web.admin.WebModel;
using ProductType = TransFormer.BLL.ProductType;

namespace TransFormer.Web.admin.AdminAshx
{
    /// <summary>
    /// ProductTypeList 的摘要说明
    /// </summary>
    public class ProductTypeList : IHttpHandler, IRequiresSessionState
    {
        private BLL.ProductType _bll = new ProductType();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int pageIndex = 1;
            int pageSize = 10;

            int.TryParse(context.Request["rows"], out pageSize);
            int.TryParse(context.Request["page"], out pageIndex);

            var dataset = _bll.GetListByPage(string.Empty, "Id", (pageIndex - 1) * pageSize + 1, pageIndex * pageSize);
            var list = _bll.DataTableToList(dataset.Tables[0]);
            
            List<ProductTypeAdmin> newList = new List<ProductTypeAdmin>();
            foreach (var productType in list)
            {
                Model.ProductTypeAdmin pa = new ProductTypeAdmin();
                pa.Id = productType.Id;
                pa.TypeName = productType.TypeName;
                pa.TypeDesc = productType.TypeDesc;
                pa.ParrentId = productType.ParrentId;
                pa.Language = productType.Language;
                var firstOrDefault = list.FirstOrDefault(x => x.Id == productType.ParrentId);
                if (firstOrDefault != null)
                    pa.ParentName = firstOrDefault.TypeName;
                newList.Add(pa);
            }

            var data = new EzuiModel<Model.ProductTypeAdmin> { rows = newList.ToArray() };
            data.total = _bll.GetRecordCount(string.Empty).ToString();
            var jz = new JavaScriptSerializer();
            var jsonData = jz.Serialize(data);
            context.Response.Write(jsonData);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}